package com.info33.platform.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.info33.platform.business.app.vo.AppCenterVO;
import com.info33.platform.common.constant.TableConstant;
import com.info33.platform.common.mvc.controller.BaseController;
import com.info33.platform.common.mvc.vo.Result;
import com.info33.platform.common.validated.SaveValidated;
import com.info33.platform.common.validated.UpdateValidated;
import com.info33.platform.system.dto.SysDeptDTO;
import com.info33.platform.system.dto.SysTenantUserDTO;
import com.info33.platform.system.dto.SysUserDTO;
import com.info33.platform.system.entity.SysUser;
import com.info33.platform.system.service.SysUserService;
import com.info33.platform.system.vo.SysUserDetailVO;
import com.info33.platform.system.vo.SysUserPerfect;
import com.info33.platform.system.vo.SysUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author admin
 */
@RestController
@RequestMapping("/SysUser")
@Api(tags = "系统 - 用户 - 登录信息")
public class SysUserController extends BaseController<SysUserService, SysUser> {

    private final SysUserService sysUserService;

    @Autowired
    public SysUserController(SysUserService sysUserService) {
        super(sysUserService);
        this.sysUserService = sysUserService;
    }

    @PostMapping(value = "/base/echo")
    @ApiOperation(value = "基础信息回显", notes = "传：mobile")
    public Result<SysUserPerfect> pcBaseEcho(
            @RequestBody SysUserDTO dto) {
        return Result.ok(sysUserService.pcBaseEcho(dto, getCurrentUser()));
    }

    @PostMapping(value = "/specificUserList/{pageNum}/{pageSize}")
    @ApiOperation(value = "pc - 获取某部门下特定用户", notes = "根据部门 id 获取，若为空则默认视为顶级")
    public Result<Page<SysUserVO>> specificUserList(
            @RequestBody SysUserDTO dto,
            @PathVariable int pageNum,
            @PathVariable int pageSize) {
        if (ObjectUtils.isEmpty(dto.getDeptDTO()) || ObjectUtils.isEmpty(dto.getDeptDTO().getId())) {
            SysDeptDTO deptDTO = new SysDeptDTO();
            deptDTO.setId(0L);
            dto.setDeptDTO(deptDTO);
        }
        return Result.ok(sysUserService.specificUserList(new Page<>(pageNum, pageSize), dto, getCurrentUser()));
    }

    @GetMapping(value = "/pc/base/info")
    @ApiOperation(value = "pc - 用户基础信息")
    public Result<SysUserVO> pcBaseInfo() {
        return Result.ok(sysUserService.pcBaseInfo(getCurrentUser()));
    }

    @PutMapping(value = "/pc/reset/password")
    @ApiOperation(value = "pc - 重置某人密码")
    public Result<Object> pcResetPassWord(
            @Validated(value = UpdateValidated.class) @RequestBody SysTenantUserDTO dto) {
        return sysUserService.pcResetPassWord(dto);
    }

    @PutMapping(value = "/pc/change/password")
    @ApiOperation(value = "修改密码", notes = "3 端通用，通过旧密码修改")
    public Result<Object> pcChangePassword(
            @Validated(value = SysUserDTO.ChangePassword.class) @RequestBody SysUserDTO dto) {
        return sysUserService.pcChangePassword(dto, getCurrentUser());
    }

    @PutMapping(value = "/sc/password/byCode")
    @ApiOperation(value = "修改密码", notes = "3 端通用，通过验证码修改。忘记密码情景")
    public Result<Object> changePasswordByCode(
            @Validated(value = SysUserDTO.ChangePasswordByCode.class) @RequestBody SysUserDTO dto) {
        return sysUserService.changePasswordByCode(dto);
    }

    @PostMapping(value = "/check/mobile")
    @ApiOperation(value = "检查手机号", notes = "是否已存在")
    public Result<Object> checkMobile(
            @RequestBody SysUserDTO dto) {
        return ObjectUtils.isEmpty(sysUserService.getOne(new QueryWrapper<SysUser>()
                .select(TableConstant.ID)
                .eq("mobile", dto.getMobile())
                .ne(TableConstant.ID, getCurrentUser().getId()))) ? Result.ok() : Result.error();
    }

    @PostMapping(value = "/check/loginName")
    @ApiOperation(value = "检查登录名", notes = "是否已存在")
    public Result<Object> checkLoginName(
            @RequestBody SysUserDTO dto) {
        return sysUserService.checkLoginName(dto, getCurrentUser());
    }

    @PostMapping(value = "/push/code")
    @ApiOperation(value = "发送验证码", notes = "3 端通用，仅是发送验证码。无特殊逻辑校验")
    public Result<Object> pushCode(
            @RequestBody SysUserDTO dto) {
        return sysUserService.pushCode(dto);
    }

    @PutMapping(value = "/change/mobile")
    @ApiOperation(value = "修改手机号", notes = "3 端通用")
    public Result<Object> changeMobile(
            @RequestBody SysUserDTO dto) {
        return sysUserService.changeMobile(dto, getCurrentUser());
    }

    @GetMapping(value = "/pc/detail")
    @ApiOperation(value = "pc - 首页 - 用户详情", notes = "当前用户基础信息 + 岗位部门信息")
    public Result<SysUserVO> pcDetail() {
        return Result.ok(sysUserService.pcDetail(getCurrentUser()));
    }

    @PostMapping(value = "/userList/{pageNum}/{pageSize}")
    @ApiOperation(value = "pc - 获取某部门下用户", notes = "根据部门 id 获取，若为空则默认视为顶级")
    public Result<Page<SysUserVO>> getUserListByDeptId(
            @RequestBody SysUserDTO dto,
            @PathVariable int pageNum,
            @PathVariable int pageSize) {
        if (ObjectUtils.isEmpty(dto.getDeptDTO()) || ObjectUtils.isEmpty(dto.getDeptDTO().getId())) {
            SysDeptDTO deptDTO = new SysDeptDTO();
            deptDTO.setId(0L);
            dto.setDeptDTO(deptDTO);
        }
        return Result.ok(sysUserService.getUserListByDeptId(new Page<>(pageNum, pageSize), dto, getCurrentUser()));
    }

    @PostMapping(value = "/getAllUser/{pageNum}/{pageSize}")
    @ApiOperation(value = "pc - 获取租户下所有用户", notes = "根据部门 id 获取，若为空则默认视为顶级")
    public Result<Page<SysUserDetailVO>> getAllUser(
            @RequestBody SysUserDTO dto,
            @PathVariable int pageNum,
            @PathVariable int pageSize) {
        return Result.ok(sysUserService.getAllUser(new Page<>(pageNum, pageSize), dto, getTenantId()));
    }

    @PostMapping("/saveUser")
    @ApiOperation(value = "新增系统用户信息")
    public Result<?> saveUser(@Validated(value = {SysUserDTO.SaveUser.class, SaveValidated.class}) @RequestBody SysUserDTO sysUserDTO) {
        return sysUserService.saveUser(sysUserDTO, getTenantId());
    }

    @PostMapping("/editUser")
    @ApiOperation(value = "更新系统用户信息")
    public Result<?> editUser(@Validated(value = {SysUserDTO.UpdateUser.class, UpdateValidated.class}) @RequestBody SysUserDTO sysUserDTO) {
        return sysUserService.editUser(sysUserDTO, getTenantId());
    }

    @GetMapping(value = "/getUserDetail/{id}")
    @ApiOperation(value = "获取用户信息详情")
    public Result<SysUserDetailVO> getUserDetail(@PathVariable Long id) {
        return Result.ok(sysUserService.getUserDetail(id));
    }

    @GetMapping(value = "/getUserDetailList/{id}")
    @ApiOperation(value = "获取用户信息详情，id多个用逗号隔开")
    public Result<List<SysUserDetailVO>> getUsersDetail(@PathVariable String id) {
        return Result.ok(sysUserService.getUserDetailList(id));
    }

    @PostMapping(value = "/search")
    @ApiOperation(value = "根据条件查询用户信息")
    public Result<?> get(@RequestBody SysUser sysUser) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>(sysUser);
        if (sysUserService.count(queryWrapper) > 1) {
            return Result.ok(sysUserService.list(queryWrapper));
        } else {
            return Result.ok(sysUserService.getOne(queryWrapper));
        }
    }

    @GetMapping(value = "/pc/editEcho/{userId}")
    @ApiOperation(value = "pc 编辑显示")
    public Result<SysUserVO> pcEditEcho(
            @PathVariable Long userId) {
        return Result.ok(sysUserService.pcEditEcho(userId));
    }

    @PutMapping(value = "/pc/clearPwdErr/{userId}")
    @ApiOperation(value = "pc 清除密码错误提示")
    public Result<Object> pcClearPwdErr(
            @PathVariable Long userId) {
        return sysUserService.pcClearPwdErr(userId);
    }


    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * app
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @GetMapping(value = "/app/center")
    @ApiOperation(value = "app 个人信息", notes = "我的")
    public Result<AppCenterVO> appCenter() {
        return Result.ok(sysUserService.appCenter(getCurrentUser().getAppTenantUserVO().getId()));
    }

    @PostMapping(value = "/app/check/loginName")
    @ApiOperation(value = "app 检查登录名")
    public Result<Object> appCheckLoginName(
            @Validated(value = SysUserDTO.AppCheckLoginName.class) @RequestBody SysUserDTO dto) {
        return ObjectUtils.isEmpty(sysUserService.getOne(new QueryWrapper<SysUser>()
                .select(TableConstant.ID)
                .eq("login_name", dto.getLoginName())
                .ne(TableConstant.ID, getCurrentUser().getId())
                .last(TableConstant.LIMIT_ONE))) ? Result.ok() : Result.error("登录名已经存在");
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * mApp
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @GetMapping(value = "/mapp/center")
    @ApiOperation(value = "mapp 基础信息")
    public Result<SysUser> mAppCenter() {
        return Result.ok(sysUserService.mAppCenter(getCurrentUser()));
    }

}